package vip.xumy.core.utils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import org.dom4j.Attribute;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import vip.xumy.core.exception.CoreException;
import vip.xumy.core.pojo.special.XmlTag;

/**	All rights reserved
 *	author:mengyxu
 *	date:2020年6月28日
 */

public class XmlUtil {
	private static final String XML_HEADER = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
	private static final String SEPARATOR = System.getProperty("line.separator");
	
	public static XmlTag readFileAsTag(File file) throws CoreException{
		SAXReader reader = new SAXReader();
		Document document;
		try {
			document = reader.read(file);
			Element node = document.getRootElement();
			return parsToTag(node);
		} catch (DocumentException e) {
			throw new CoreException("解析XML文件失败");
		}
	}
	
	private static XmlTag parsToTag(Element node) {
		XmlTag tag = new XmlTag();
		tag.setName(node.getName());
		List<Attribute> list = node.attributes();
		if (list != null && !list.isEmpty()) {
			Map<String, String> attrs = new HashMap<>();
			for (Attribute attr : list) {
				attrs.put(attr.getName(), attr.getValue());
			}
			tag.setAttrs(attrs);
		}
		Iterator<Element> iter = node.elementIterator();
		if(iter.hasNext()) {
			List<XmlTag> nodes = new ArrayList<>();
			while (iter.hasNext()){
				nodes.add(parsToTag(iter.next()));
			}
			tag.setNodes(nodes);
		}else {
			tag.setValue(node.getStringValue());
		}
		return tag;
	}
	
	public static String formatTagAsXml(XmlTag tag) {
		return XML_HEADER + toXml(tag, 0);
	}
	
	private static String toXml(XmlTag tag, int idx) {
		StringBuffer sb = new StringBuffer();
		apendTab(idx, sb);
		sb.append("<").append(tag.getName());
		Map<String, String> attrs = tag.getAttrs();
		String flag = null;
		if(attrs != null && !attrs.isEmpty()) {
			for (String key : attrs.keySet()) {
				String val = attrs.get(key);
				if(key.equals("type")) {
					flag = val;
				}
				sb.append(" ").append(key).append("=\"")
				.append(val).append("\"");
			}
		}
		sb.append(">");
		List<XmlTag> nodes = tag.getNodes();
		if(nodes != null && !nodes.isEmpty()) {
			for (XmlTag node : nodes) {
				sb.append(toXml(node, idx+1));
			}
			apendTab(idx, sb);
		}else {
			String value = tag.getValue();
			if("isdn".equals(flag)) {
				sb.append(format("19" + value));
			}else if("imsi".equals(flag)) {
				sb.append(format(value));
			}else {
				sb.append(value);
			}
		}
		sb.append("</").append(tag.getName()).append(">");
		return sb.toString();
	}
	
	private static void apendTab(int idx, StringBuffer sb) {
		sb.append(SEPARATOR);
		for (int i = 0; i < idx; i++) {
			sb.append("  ");
		}
	}
	
	private static String format(String str) {
		int len = str.length();
		if(len%2 != 0) {
			str += "F";
		}
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < str.length()/2; i++) {
			sb.append(str.charAt(i*2+1)).append(str.charAt(i*2)).append(" ");
		}
		return sb.substring(0, sb.length()-1);
	}
	
	public static String parse(String str) {
		if(StringUtil.isEmpty(str)) {
			return "";
		}
		str = str.trim().replace(" ", "");
		StringBuffer sb = new StringBuffer();
		for (int i = 0; i < str.length()/2; i++) {
			sb.append(str.charAt(i*2+1)).append(str.charAt(i*2));
		}
		return sb.substring(0, sb.length()-1).replace("F", "");
	}


}
